package com.retail.order.service.impl;

import com.retail.common.core.domain.Result;
import com.retail.order.domain.Address;
import com.retail.order.mapper.AddressMapper;
import com.retail.order.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class AddressServiceImpl implements AddressService {
    @Autowired
    AddressMapper addressMapper;

    @Override
    public Result list() {
        List<Address> list = addressMapper.list();
        List<Address> collect = list.stream().filter(address -> {
            return address.getAddrPid() == 0;
        }).map(address -> {
            address.setChildren(getChildren(list, address).isEmpty() ? null : getChildren(list, address));
            return address;
        }).sorted(new Comparator<Address>() {
            @Override
            public int compare(Address o1, Address o2) {
                return Integer.parseInt(o1.getAddrCode()) - Integer.parseInt(o2.getAddrCode());
            }
        }).collect(Collectors.toList());
        return Result.success(collect);
    }

    private List<Address> getChildren(List<Address> list, Address address){
        List<Address> collect = list.stream().filter(address1 -> {
            return Objects.equals(address1.getAddrPid(), address.getAddrId());
        }).map(address1 -> {
            address1.setChildren(getChildren(list, address1).isEmpty() ? null : getChildren(list, address1));
            return address1;
        }).sorted(new Comparator<Address>() {
            @Override
            public int compare(Address o1, Address o2) {
                return Integer.parseInt(o1.getAddrCode()) - Integer.parseInt(o2.getAddrCode());
            }
        }).collect(Collectors.toList());
        return collect;
    }


    //
//    public List<Address> listTree(Address address){
//        List<Address> lists = this.list(address);
//        return lists.stream()
//                .filter(addr -> addr.getParentId() == 0)
//                .peek(addr ->addr.setChildren(getChildren(addr,lists).isEmpty() ? null : getChildren(addr, lists)))
//                .collect(Collectors.toList());
//
//    }
//
//    private List<Address> getChildren(Address address, List<Address> lists) {
//        return lists.stream()
//                .filter(addr -> addr.getParentId().equals(addr.getAddrId()))
//                .peek(addr -> addr.setChildren(getChildren(addr, lists).isEmpty() ? null : getChildren(addr, lists)))
//                .collect(Collectors.toList());
//    }
}
